package com.miyu.system.service.sys.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.miyu.common.utils.commonUtils.Comutils;
import com.miyu.system.dao.system.SysTaskDao;
import com.miyu.system.dao.system.SysTaskGroupDao;
import com.miyu.system.pojo.system.SysTask;
import com.miyu.system.pojo.system.SysTaskGroup;
import com.miyu.system.service.sys.TaskJobService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 任务工作服务impl
 * @author longm
 * @date 2022/12/31
 */
@Slf4j
@Service
public class TaskJobServiceImpl implements TaskJobService {
    @Autowired
    private Scheduler scheduler;
    @Resource
    private SysTaskDao  sysTaskDao;
    @Resource
    private SysTaskGroupDao sysTaskGroupDao;


    /**
     * addjob 创建并启动任务
     * @param job 工作
     * @return {@link JSONObject}
     */
    @Override
    public JSONObject addjob(JSONObject job) {
        System.out.println(job);
        /** 任务名称*/
        String jName = job.getString("taskId");
        /** 任务分组*/
        String jGroup = job.getString("groupId");
        /** 触发器名称*/
        String tName = job.getString("taskId");
        /** 触发器分组*/
        String tGroup = job.getString("groupId");
        String cron = job.getString("taskCron");

        try {
            System.out.println(scheduler.checkExists(JobKey.jobKey(jName, jGroup)));
            //判断启动是否存在如果存在直接启动 否则创建新的任务启动
            if(scheduler.checkExists(JobKey.jobKey(jName, jGroup))){
                scheduler.resumeJob(JobKey.jobKey(jName, jGroup));
            }else{
         //    构建JobDetail
            JobDetail jobDetail = JobBuilder.newJob(BuildTaskJob.class)
                    .withIdentity(jName, jGroup)
                    .build();
            // 按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(tName, tGroup)
                    .startNow()
                    .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                    .build();
            // 启动调度器
            scheduler.start();
            scheduler.scheduleJob(jobDetail, trigger);
            }
        } catch (Exception e) {
            log.info("创建定时任务失败" + e);
        }
        return null;
    }

    /**
     * pausejob
     * 任务暂停
     * @param job 工作
     * @return {@link JSONObject}
     */
    @Override
    public JSONObject pausejob(JSONObject job)  {
        String jName = job.getString("taskId");
        String jGroup = job.getString("groupId");
        try {
            scheduler.pauseJob(JobKey.jobKey(jName, jGroup));
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    /**
     * 重启定时任务
     * @param job 工作
     * @return {@link JSONObject}
     */
    @Override
    public JSONObject resumeJob(JSONObject job) {
        String jName = job.getString("jName");
        String jGroup = job.getString("jGroup");
        try {
            scheduler.resumeJob(JobKey.jobKey(jName, jGroup));
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    /**
     * 删除任务
     * @param job 工作
     * @return {@link JSONObject}
     */
    @Override
    public JSONObject deleteJob(JSONObject job) {
        String jName = job.getString("jName");
        String jGroup = job.getString("jGroup");
        try {
            scheduler.deleteJob(JobKey.jobKey(jName, jGroup));
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    /**
     * 保存编辑系统任务
     * @param job 工作
     * @return {@link JSONObject}
     */
    @Override
    @Caching(evict={@CacheEvict(cacheNames = "system:sysTask:sysTask" ,key="'sysTask'")})
    @CachePut(cacheNames = "system:sysTask:sysTask" ,key="#result.getTaskId()")
    public SysTask editSysTask(JSONObject job) {
        SysTask sysTask = JSONObject.parseObject(job.toString(),SysTask.class);
        if(StringUtils.isBlank(sysTask.getTaskId())){
            sysTask.setTaskId(Comutils.getUUID());
        }
        sysTaskDao.saveOrUpdateByNotNullProperties(sysTask);
        return sysTask;
    }

    /**
     * 编辑系统任务集团
     * @param job 工作
     * @return {@link SysTaskGroup}
     */
    @Override
    @Caching(evict={@CacheEvict(cacheNames = "system:sysTask:taskGroup" ,key="'taskGroup'")})
    @CachePut(cacheNames = "system:sysTask:taskGroup" ,key="#result.getGroupId()")
    public SysTaskGroup editSysTaskGroup(JSONObject job) {
        SysTaskGroup sysTaskGroup = JSONObject.parseObject(job.toString(),SysTaskGroup.class);
        if (StringUtils.isBlank(sysTaskGroup.getGroupId())){
            sysTaskGroup.setGroupId(Comutils.getUUID());
        }
        sysTaskGroupDao.saveOrUpdateByNotNullProperties(sysTaskGroup);
        return sysTaskGroup;
    }

    /**
     * 获取系统任务集团字典
     * @return {@link JSONArray}
     */
    @Override
//    @Cacheable(cacheNames  = "system:sysTask:taskGroup" ,key = "'dict'")
    public JSONArray getSysTaskGroupDict() {
        List<SysTaskGroup> sysTaskGroupsList = sysTaskGroupDao.findAll();
        return  JSONArray.parseArray(JSONObject.toJSONString(sysTaskGroupsList));
    }

    /**
     * 查询任务
     * @param job 工作
     * @return {@link JSONArray}
     */
    @Override
    public JSONArray querySysTask(JSONObject job) {
        StringBuffer sql = new StringBuffer();
        sql.append("select st.task_id,st.group_id,st.task_cron,st.task_name,st.task_num,st.task_param,  st.task_type,st.task_url,st.task_mome, ");
        sql.append(" gt.trigger_state,case gt.trigger_state when 'WAITING' then 1 when 'ACQUIRED'  then 1  else '0' end taskStatus ");
        sql.append("from sys_task st left join qrtz_triggers  gt on st.task_id = gt.job_name ");
        JSONArray rs = sysTaskDao.queryJSONArrayBySql(sql.toString());
        return rs;
    }

    @Override
    @Cacheable(cacheNames  = "system:sysTask:sysTask" ,key = "#taskId")
    public SysTask getSysTaskById(String taskId) {
        SysTask sysTask = sysTaskDao.findById(taskId).orElse(null);
        return sysTask;

    }
}
